<?php
namespace XWAM\Addon\PXCallSystem\Controller;
/**
 * Description of CtiTesterController
 *
 * @author Alen
 */
class CtiTesterController extends AppbaseController {

    // 恢复保持处理
    public function seat_callpark_save() {
        $chnl1 = I('chnl1');
        $chnl2 = I('chnl2');
        $opt = I('opt');

        $astsm = create_asmanager();
        if (!$chnl1 || !$chnl2) {
            die('通道号无效！<a href="' . AddonU('CtiTester/seat_callpark') . '">返回</a>');
        }
        //kerry修改代码块 == 开始
        /*
          // 方法1
          if ($opt == 'n') {
          $cmd = 'Stopped music on hold on ' . $chnl2;
          $result = $astsm->Command($cmd);
          echo $cmd . '<br />执行结果：';
          var_export($result);
          } else {
          $cmd = 'channel redirect ' . $chnl1;
          $cmd = "Started music on hold, class 'default', on " . $chnl1;
          $result = $astsm->Command($cmd);
          echo $cmd . '<br />执行结果：';
          var_export($result);
          }
         */
        /*
          // 方法2
          $params = array('ControllerID' => '1', 'Channel' => $chnl1, 'Channel2' => $chnl2, 'Timeout' => null, 'Parkinglot' => null);
          $result = $astsm->send_request('Park', $params);
          echo "<br />参数:<br />";
          var_export($params);
          echo '<br />执行结果:<br />';
          var_export($result);
         */

        // 方法3
        $params = array('Channel' => $chnl1, 'Event' => 'hold');
        $result = $astsm->send_request('SIPnotifychan', $params);
        echo "<br />参数:<br />";
        var_export($params);
        echo '<br />执行结果:<br />';
        var_export($result);

        //kerry修改代码块 == 结束
        echo '<br ><a href="' . AddonU('CtiTester/seat_callpark') . '">返回</a>';
    }

    // 恢复保持界面
    public function seat_callpark() {
        $this->assign('content', asmanager_query_result('core show channels concise'));
        $this->display();
    }

    //put your code here
    public function index() {
        $this->display();
    }

    public function test_status() {
        $cmd = I('cmd');
        $this->assign('cmd', $cmd);
        if ($cmd) {
            if (false !== ($pos = strpos($cmd, ' '))) {
                $prefix = strtoupper(substr($cmd, 0, $pos));
            }
            if ($prefix == "NOT_INUSE") {
                $exten = trim(substr($cmd, 10));
                $list = asmanager_query_result("database put CustomDevstate DEVDND$exten NOT_INUSE");
                $list.= asmanager_query_result("database put CustomDevstate DND$exten NOT_INUSE");
            } else {
                $list = asmanager_query_result($cmd);
            }
            $this->assign('list', $list);
        }
        $this->display();
    }

    /**
     * 测试队列添加操作
     */
    public function queue_opt_save() {
        $opt = I('opt');
        $queue = I('queue');
        $extension = I('extension');
        $err = '';
        if (!$opt)
            $err .= '请选择操作!<br />';
        if (!$queue)
            $err .= '请选择分机!<br />';
        if (!$extension)
            $err .= '请选择分机!</br />';
        if ($err) {
            $this->ajaxMsg(false, $err);
        }
        switch ($opt) {
            case 'login':
            case 'loginout':
                $result = $this->login_extension_static($queue, $extension, $opt);
                break;
        }
        if ($result['result']) {
            $this->ajaxMsg(true, '操作成功');
        } else {
            $this->ajaxMsg(false, '操作失败：' . $result['Message']);
        }
    }

    // 登入静态分机,支持多个分机批量操作 
    function login_extension_static($queue, $extension, $opt = 'login') {
        $astman = create_asmanager();
        $queue = $queue;
        if (is_array($extension)) {
            $extens = $extension;
        } else {
            $extens = explode(',', $extension);
        }
        foreach ($extens as $exten) {
            $interface = 'SIP/' . $exten;
            if ($opt == 'login') {
                //$result = $astman->QueueAdd($queue, $interface);  // 不能用这种方式签入,这种方式登入结果是SIP/301,正确的是301 (SIP/301)
                $result = $astman->Command('queue add member SIP/' . $exten . ' to ' . $queue . ' penalty 0 as ' . $exten . ' state_interface SIP/' . $exten);
                $isSuccess = strpos($result['data'], 'Added interface') !== false;
            } else {
                $result = $astman->QueueRemove($queue, $interface); // 移除队列
                $isSuccess = $result['Response'] == 'Success';
            }
        }
        return array('result' => $isSuccess, 'Message' => $result['Message']);
    }

    /**
     * 发起呼叫
     * 成功则返回true,否则返回错误消息
     * @param $phoneNumber
     * @param $trunkName
     * @param $context
     * @param $callerNo
     * @return bool
     * @since 1.0 2014-12-5 by sutroon 重构
     */
    function dialout_func($extension, $phoneNumber, $trunkName, $context, $callerNo) {
        //set_time_limit(0);
        //ob_implicit_flush(false);

        $astman = create_asmanager();
        $params = array(
            'Channel' => "SIP/$extension", // 如果是电话则 Local/015003069007@user
            'Application' => 'Dial',
            'Data' => "SIP/$trunkName/$phoneNumber",
            'Priority' => 1,
            'Timeout' => 45000, // 等待被叫应答振铃时间
                // 'CallerID'=>$callerNo, // 来电显示的号码
                // 'Exten'=>'', 调用的拨号方案，对方接听电话后我们在这里实现交互
        );
        $result = $astman->send_request('Originate', $params);
        return $result['Response'] == 'Success' ? true : $result['Message'];
    }

    public function dial_save() {
        $params = new \Org\Su\Params();
        $params->addParam('phoneNumber', 'require', '电话号码未填写');
        $params->addParam('trunkName', 'require', '中继名称未选择');
        $params->addParam('context', 'require', '流程名称未填写');
        if (I('regMode') == 'register') {
            $params->addData('callerNo', '05925137888');
        } else {
            $params->addParam('callerNo', 'require', '主叫号码未填写');
        }
        if ($params->hasError()) {
            $this->ajaxMsg(false, $params->getError());
        }
        $data = $params->getParams(null, array('phoneNumber', 'trunkName', 'context', 'callerNo'));
        $result = $this->dialout_func($data['phoneNumber'], $data['phoneNumber'], $data['trunkName'], $data['context'], $data['callerNo']);
        if (true === $result) {
            $this->ajaxMsg(true, '正在发起呼叫...', '', 20);
        } else {
            $this->ajaxMsg(false, '呼叫失败 [' . $result . ']');
        }
    }

    public function conf_list() {
        if (I('q') == 'all') {
            $files = array();
            $dir_path = '/etc/asterisk/';
            if ($handle = opendir($dir_path)) {
                while (false !== ($file = readdir($handle))) {
                    if ($file == "." || $file == "..") {
                        continue;
                    }
                    $files[] = $file;
                }
                closedir($handle);
            }
        } else {
            $files = explode(',', 'adsi.conf,adtranvofr.conf,agents.conf,alarmreceiver.conf,alsa.conf,amd.conf,asterisk.conf,cbmysql.conf,cdr_custom.conf,cdr_manager.conf,cdr_mysql.conf,cdr_pgsql.conf,cdr_tds.conf,chan_dahdi.conf,chan_dahdi_additional.conf,cli.conf,codecs.conf,console.conf,dahdi-channels.conf,dnsmgr.conf,dundi.conf,enum.conf,extconfig.conf,extensions.conf,extensions_additional.conf,extensions_custom.conf,extensions_hud.conf,extensions_minivm.conf,extensions_override_freepbx.conf,features.conf,features_applicationmap_additional.conf,features_applicationmap_custom.conf,features_featuremap_additional.conf,features_featuremap_custom.conf,features_general_additional.conf,features_general_custom.conf,festival.conf,flite.conf,followme.conf,freepbx_featurecodes.conf,freepbx_module_admin.conf,func_odbc.conf,globals_custom.conf,gtalk.conf,h323.conf,http.conf,iax.conf,iax_additional.conf,iax_custom.conf,iax_custom_post.conf,iax_general_additional.conf,iax_general_custom.conf,iax_registrations.conf,iax_registrations_custom.conf,iaxprov.conf,indications.conf,jabber.conf,jingle.conf,localprefixes.conf,logger.conf,manager.conf,manager_additional.conf,manager_custom.conf,meetme.conf,meetme_additional.conf,mgcp.conf,minivm.conf,misdn.conf,mobile.conf,modem.conf,modules.conf,musiconhold.conf,musiconhold_additional.conf,musiconhold_custom.conf,muted.conf,mysql.conf,ooh323.conf,osp.conf,oss.conf,phone.conf,phoneprov.conf,phpagi.conf,privacy.conf,queuerules.conf,queues.conf,queues_additional.conf,queues_custom.conf,queues_custom_general.conf,queues_general_additional.conf,queues_post_custom.conf,res_ldap.conf,res_mysql.conf,res_odbc.conf,res_pgsql.conf,res_snmp.conf,rpt.conf,rtp.conf,say.conf,sip.conf,sip_additional.conf,sip_custom.conf,sip_custom_post.conf,sip_general_additional.conf,sip_general_custom.conf,sip_nat.conf,sip_notify.conf,sip_registrations.conf,sip_registrations_custom.conf,skinny.conf,sla.conf,smdi.conf,udptl.conf,unistim.conf,usbradio.conf,users.conf,vm_email.inc,vm_general.inc,voicemail.conf,vpb.conf,zapata_additional.conf');
        }
        sort($files);
        $str = '<a href="' . AddonU('CtiTester/conf_list', 'q=all') . '"  class="easyui-linkbutton">所有配置文件</a><a href="' . AddonU('CtiTester/conf_list') . '"  class="easyui-linkbutton">常用配置文件</a><br />';
        $str .= '<table class="table-list"><tr><th>序号</th><th>文件名</th><th>操作</th></tr>';
        $i = 1;
        foreach ($files as $file) {
            $str .= '<tr><td>' . $i . '</td><td>' . $file . '</td><td><a href="' . AddonU('CtiTester/conf_view', 'n=' . $file) . '"  class="easyui-linkbutton">查看</a></td></tr>';
            $i++;
        }
        $str .= '</table>';
        $this->assign('str', $str);
        $this->display();
    }

    public function conf_view() {
        $n = I('n');
        if (!$n)
            die('参数有误!');
        $dir_path = '/etc/asterisk/';
        $filename = $dir_path . $n;
        $str = file_get_contents($filename);
        $this->assign('file', $n);
        $this->assign('str', $str);
        $this->display();
    }

    // 重载cti
    public function reload_sip() {
        $result = M('asterisk.admin')->where("variable = 'need_reload'")->setField('value', 'false');
        // asmanager_query_result(array('sip reload',':moh reload',':reload'));
        asmanager_query_result('core reload');
        $this->ajaxReturn(array('status' => strval(false !== $result)));
    }

    // 判断cti是否需要重载
    public function check_cti_need_reload() {
        $result = M('asterisk.admin')->where("variable = 'need_reload' and value='true'")->count();
        $this->ajaxReturn(array('status' => $result));
    }

}
